<template>
<!--待投保  分组后的页面-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
<!--      <el-form-item label="投保方案名称" prop="employeeName">-->
<!--        <el-input-->
<!--          v-model="queryParams.projectName"-->
<!--          placeholder="请输入投保方案名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="投保属性" prop="property">
        <el-select
          v-model="queryParams.property"
          placeholder="请选择投保属性"
          clearable
        >
          <el-option
            key="1"
            label="主单"
            value="1"/>
          <el-option
            key="2"
            label="批单"
            value="2"/>
        </el-select>
      </el-form-item>

      <el-form-item label="签约主体" prop="signMainId">
        <el-select
          v-model="queryParams.signMainId"
          placeholder="请选择签约主体公司"
          clearable
        >
          <el-option
            v-for="item in allSignMainList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="客户企业(二级)" prop="selectNameSecond">
        <el-input
          v-model="queryParams.selectNameSecond"
          placeholder="请输入客户企业"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="业务类型" prop="businessTypeId">
        <el-select
          v-model="queryParams.businessTypeId"
          placeholder="请选择业务类型"
          clearable
        >
          <el-option
            v-for="item in allBusinessTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="投保月份" prop="insuranceMonth">
        <el-date-picker clearable
                        v-model="queryParams.insuranceMonth"
                        type="month"
                        value-format="yyyy-MM"
                        placeholder="请选择投保月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['employeeProject:employeeProject:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['employeeProject:employeeProject:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['employeeProject:employeeProject:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['employeeProject:employeeProject:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->

<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          icon="el-icon-folder-checked"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleApproved"-->
<!--          v-hasPermi="['employeeProject:employeeProject:approved']"-->
<!--        >审核通过</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleInsureExport"
          v-hasPermi="['employeeProject:employeeProject:insureExport']"
        >投保导出</el-button>
      </el-col >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleInsureImport"
          v-hasPermi="['employeeProject:employeeProject:insureImport']"
        >投保导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

    <el-table v-loading="loading" :data="employeeProjectList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="保单属性" align="center" prop="property" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.insurance_policy_property" :value="scope.row.property"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="签约主体公司" align="center" prop="signMain.name" />
<!--      <el-table-column label="供应商" align="center" prop="supplierName" />-->
      <el-table-column label="客户企业(二级)" align="center" prop="company.nameSecond" />
      <el-table-column label="所属合同" align="center" prop="agreement.name" />
      <el-table-column label="业务类型" align="center" prop="businessType.name" />
<!--      <el-table-column label="投保方案" align="center" prop="supplierName" />-->
      <el-table-column label="生效日期" align="center" prop="insuranceStart" />
      <el-table-column label="失效日期" align="center" prop="insuranceEnd" />
<!--      <el-table-column prop="type" label="投保类别" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.personnel_insurance_type" :value="scope.row.type"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="总人数" align="center" prop="totalCountPeopleNum" />
      <el-table-column label="待投保人数" align="center" prop="totalPeopleNum" />
      <el-table-column label="待投保人次" align="center" prop="totalPeopleTime" />
      <el-table-column label="投保人数" align="center" prop="alreayTotalPeopleNum" />
      <el-table-column label="投保人次" align="center" prop="alreayTotalPeopleTime" />
<!--      <el-table-column label="实际投保人数" align="center" prop="touBaoTotalPeopleNum" />-->
<!--      <el-table-column label="实际投保人次" align="center" prop="touBaoTotalPeopleTime" />-->
      <el-table-column label="投保状态" align="center" prop="flag" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.personnel_insurance_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime== null ? scope.row.createTime :scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="删除状态" align="center" prop="delFlag" />-->
<!--      <el-table-column label="参与付款情况" align="center" prop="paymentStatus" >-->
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.paymentStatus == '0'">未参与付款</span>-->
<!--          <span v-if="scope.row.paymentStatus == '1'">已参与付款</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="参与结算情况" align="center" prop="settlementStatus" >-->
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.settlementStatus == '0'">未参与结算</span>-->
<!--          <span v-if="scope.row.settlementStatus == '1'">已参与结算</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showDetail(scope.row)"
            v-hasPermi="['employeeProject:employeeProject:showDetailWaitInsured']"
          >查看投保详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!--审核对话框-->
    <el-dialog  :title="auditTitle"  :visible.sync="auditOpen" width="700px">
      <el-form ref="auditForm" :model="auditForm">
        <el-form-item label="原因" prop="remark">
          <el-input v-model="auditForm.remark"  type="textarea" placeholder="请输入原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAuditConfirm">确 定</el-button>
        <el-button @click="auditOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入投保结果名单对话框 -->
    <el-dialog :title="importInsureResult.title" :visible.sync="importInsureResult.open" width="700px">
      <el-form ref="importInsureResultForm" :model="importInsureResultForm" :rules="importInsureResultRules" label-width="120px" >
        <!--        <el-form-item label="供应商"  prop="supplierId">-->
        <!--          <el-select v-model="importInsureResultForm.supplierId" placeholder="请选择供应商" clearable filterable>-->
        <!--            <el-option-->
        <!--              v-for="item in allSupplierList"-->
        <!--              :key="item.id"-->
        <!--              :label="item.name"-->
        <!--              :value="item.id"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="投保月份" prop="insuranceMonth">-->
        <!--          <el-date-picker clearable-->
        <!--                          v-model="importInsureResultForm.insuranceMonth"-->
        <!--                          type="month"-->
        <!--                          value-format="yyyy-MM"-->
        <!--                          placeholder="请选择投保月份">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->

        <el-form-item label="上传附件" >
          <el-upload
            ref="importInsureResult"
            :limit="1"
            :file-list="importInsureResultList"
            accept=".xlsx, .xls"
            action=""
            :disabled="importInsureResult.isUploading"
            :on-progress="handleImportInsureResultProgress"
            :on-success="handleImportInsureResultSuccess"
            :on-change="handleImportInsureResultChange"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
<!--            <div class="el-upload__tip" slot="tip">-->
<!--              &lt;!&ndash;                        <el-checkbox v-model="importInsureResult.updateSupport" />是否更新已经存在的用户数据&ndash;&gt;-->
<!--              <el-link type="info" style="font-size:16px;color:dodgerblue" @click="importTemplate">下载模板</el-link>-->
<!--            </div>-->
            <div class="el-upload__tip" style="color:red" slot="tip">提示：<br/>1.仅支持单文件导入，且格式为“xls”或“xlsx”！<br/>2.利用【投保导出】的Excel，依实际投保情况，修改【投保状态】后进行导入！</div>
          </el-upload>
          <!-- 进度条 -->
          <el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImportInsureResultForm" v-loading.fullscreen.lock="fullscreenLoading">确 定</el-button>
        <el-button @click="cancelImportInsureResultForm">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addEmployeeProject,
  approvedEmployeeProject,
  delEmployeeProject,
  getEmployeeProject,
  listEmployeeProject,
  updateEmployeeProject,
  auditRefuse,
  listGroupByCompanyAndProperty,
  listGroupByCompanyAndPropertyWaitInsured,
  back
} from "@/api/employee_project/employeeproject";
import {listAllInsuranceProject} from "@/api/insurance_project/insuranceproject";
import {
  importInsureResult,
  listInsucance
} from "@/api/insucance/insucance";
import {getToken} from "@/utils/auth";
import {listAllBusinessType} from "@/api/business_type/businesstype";
import {listAllSignMain} from "@/api/sign_main/signmain";

export default {
  name: "WaitInsuredGroup",
  dicts: ['personnel_insurance_status','personnel_insurance_audit_status','personnel_insurance_type','insurance_policy_property'],

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 投保人员与保险方案中间表格数据
      employeeProjectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      fullscreenLoading:false,
      // 查询参数
      queryParams: {
        orderByColumn:'m.update_time',
        isAsc:'desc',
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        employeeId: null,
        type: null,
        auditStatus: "1",
        status: null,
        delFlag: '0',
        backStatus:"0",
        paymentStatus: null,
        settlementStatus: null,
        employeeName:null,
        projectName:null,
        insuranceMonth :null,
        companyName:null,
        selectNameSecond:null,
        signMainId:null,
        businessTypeId:null,
        property: null,
        insuranceStart: null,
        agreementId: null,
        statusList:["0","1","2"]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //删除状态下拉框
      options: [{
        value: '0',
        label: '未删除'
      }, {
        value: '1',
        label: '已删除'
      }],
      // 全投保方案列表
      allInsuranceProjectList: [],
      // 导入投保结果名单
      importInsureResult: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + ""
      },
      importInsureResultForm:{},
      importInsureResultRules:{
        insuranceMonth: [{ required: true, message: "请选择投保月份", trigger: "blur" }],
        importInsureResultList: [{ required: true, message: "请先上传投保结果附件", trigger: "blur" }],
      },
      importInsureResultList:[],

      //审核弹窗
      auditOpen:false,
      //审核form
      auditForm:{},
      //审核title
      auditTitle:"",
      //业务类型
      allBusinessTypeList:[],
      //签约主体list
      allSignMainList:[],

      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
      timer: null, //定时器,

    };
  },
  created() {
    this.getList();
    this.getInsuranceProjectList();
    this.getBusinessTypeList();
    this.getSignMainList();
  },
  methods: {
    /** 查询投保人员与保险方案中间列表 */
    getList() {
      this.loading = true;
      listInsucance(this.queryParams).then(response => {
        this.employeeProjectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取投保方案列表
    getInsuranceProjectList(){
      let q= {};
      listAllInsuranceProject(q).then(response => {
        this.allInsuranceProjectList = response;
      });
    },
    // 获取业务类型列表
    getBusinessTypeList() {
      let q = {};
      listAllBusinessType(q).then(response => {
        this.allBusinessTypeList = response;
      });
    },
    // 获取签约主体列表
    getSignMainList() {
      let q = {};
      listAllSignMain(q).then(response => {
        this.allSignMainList = response;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        employeeId: null,
        type: null,
        auditStatus: null,
        status: null,
        delFlag: null,
        paymentStatus: null,
        settlementStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        employeeName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加投保人员与保险方案";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEmployeeProject(id).then(response => {
        this.form = response.data;
        if (response.data.employee!=null){
          this.form.employeeName = response.data.employee.name;
        }
        this.open = true;
        this.title = "修改人员投保详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEmployeeProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEmployeeProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除投保人员与保险方案编号为"' + ids + '"的数据项？').then(function() {
        return delEmployeeProject(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('employeeProject/employeeProject/export', {
        ...this.queryParams
      }, `employeeProject_${new Date().getTime()}.xlsx`)
    },

    /** 审核通过操作 */
    handleApproved(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认【审核通过】编号为"' + ids + '"的数据项？').then(function() {
        return approvedEmployeeProject(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("【审核通过】成功");
      }).catch(() => {});
    },

    /** 投保导出按钮操作 */
    handleInsureExport() {
      let q = {
        ids : this.ids
      }
      this.download('insucance/insucance/insureExport', {
         ...q
      }, `待投保数据_${new Date().getTime()}.xlsx`)
    },

    /** 投保导入按钮操作 */
    handleInsureImport() {
      this.importInsureResultForm = {};
      this.importInsureResult.title = "导入投保结果";
      this.importInsureResult.open = true;
      this.loadProgress = 0;
      this.progressFlag = false;
    },

    //投保结果导入中
    handleImportInsureResultProgress(event, file, fileList) {
      this.importInsureResult.isUploading = true;
    },
    // 投保结果导入成功处理
    handleImportInsureResultSuccess(response, file, fileList) {
      this.importInsureResult.open = false;
      this.importInsureResult.isUploading = false;
      this.$refs.importInsureResult.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 100vh;padding: 10px 10px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    handleImportInsureResultChange(file, fileList){
      this.importInsureResultList = fileList;
    },
    //设置定时器
    setTime() {
      //每隔一秒钟运行一次保存方法
      this.timer = setInterval(() => {
        this.addPercent();
      }, 1000)
    },
    //定时器执行的任务
    addPercent() {
      if (this.loadProgress !== 100) {
        this.loadProgress += 5;
      } else {
        clearInterval(this.timer);　　// 清除定时器
        this.timer = null;
        this.$alert("【提示】：后台正在上传，请稍后再做操作！");
        this.loading = false;
        this.fullscreenLoading = false;
        this.importInsureResult.open = false;
        this.importInsureResult.isUploading = false;
        this.$refs.importInsureResult.clearFiles();
        this.importInsureResultForm = {};
        this.importInsureResultList = [];
        //this.getList();
      }
    },
    // 提交导入投保结果
    submitImportInsureResultForm(){
      this.$refs["importInsureResultForm"].validate(valid => {
        if (valid) {
          let importInsureResultForm = new FormData();
          if (this.importInsureResultList.length > 0 && this.importInsureResultList[0] != null) {
            importInsureResultForm.append('file', this.importInsureResultList[0].raw);
          }
          // importInsureResultForm.append('insuranceMonth', this.importInsureResultForm.insuranceMonth);
          // console.log(importInsureResultForm);
          //进度条开启
          this.progressFlag = true;
          this.setTime()
          this.fullscreenLoading = true;
          importInsureResult(importInsureResultForm).then(response => {
            this.fullscreenLoading = false;
            this.importInsureResult.open = false;
            this.importInsureResult.isUploading = false;
            this.$refs.importInsureResult.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 50vh;padding: 10px 10px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
            //返回数据后进度条结束 清除定时器
            this.loadProgress = 100
            clearInterval(this.timer);
            this.timer = null;
          });
        }
      });
    },
    //取消上传历史理赔
    cancelImportInsureResultForm(){
      this.importInsureResult.open = false;
      this.importInsureResultList = [];
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('insucance/insucance/importTemplate', {
      }, `投保导入模板_${new Date().getTime()}.xlsx`)
    },

    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },

    //审核弹窗打开  type 1 审核拒绝   2 拒保
    handleOpenAudit(row,cate){
      // console.log('type',cate);
      // console.log('row',row);
      this.auditForm = {};
      this.auditForm.cate = cate;
      this.auditForm.id = row.id;
      this.auditTitle = cate === 1 ? "拒绝审核" :"拒保";
      this.auditOpen = true;
    },
    //点击了确定
    handleAuditConfirm(){
      back(this.auditForm).then(response => {
        this.$modal.msgSuccess("退回成功");
        this.auditOpen = false;
        this.getList();
      });

    },


    //投保
    handleInsure(row){
      let data = {
        "id":row.id,
        "status":"3"
      }
      this.$modal.confirm('是否确认【投保】编号员工姓名为"' + row.employee.name + '"方案名称为"'+row.project.name+'"的数据项？').then(function() {
        return updateEmployeeProject(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("【审核通过】成功");
      }).catch(() => {});
    },

    //格式化
    propertyFormatter(row) {
      switch (row.property) {
        case '1':
          return '主单'
        case '2':
          return '批单'
      }
    },

    //查看详情
    showDetail(row){
      // console.log(row);
      this.$router.push({ path: '/center_insured/WaitInsured/', query: { property: row.property,companyId:row.company.id,insuranceStart:row.insuranceStart,agreementId:row.agreement.id,signMainId:row.signMain.id,insucanceId:row.id }})
    },

    handleBack(row){
      this.auditForm = {
        "companyId":row.companyId,
        "property":row.property,
        "insuranceStart":row.insuranceStart,
        "agreementId":row.agreementId
      }
      this.auditOpen = true;
      this.auditTitle ="退回原因";
    }




  }
};
</script>

